package com.fanqj.sentinel.controller;

import com.alibaba.csp.sentinel.AsyncEntry;
import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphO;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.context.ContextUtil;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;

/**
 * @author <a href="mailto:fanqijin@wxchina.com">fanqj</a>
 * @Date 2021年02月01日 10:47
 * @Version 6.4.1
 */
@RestController
@RequestMapping("/sentinel")
public class SentinelController {

    /**
     * try-with-resource方式
     * @return
     */
    @GetMapping("/first")
    public String firstTest() {
        //定义资源
        try (Entry entry = SphU.entry("firstResource")) {
            // 被保护的业务逻辑
            return "Hello first sentinel demo!";
        } catch (BlockException e) {
            // 资源访问阻止，被限流或被降级
            e.printStackTrace();
            return "Block by sentinel!";
        }
    }

    /**
     * try-catch-finally方式
     * @return
     */
    @GetMapping("/second")
    public String secondTest() {
        //定义资源
        Entry entry = null;
        try {
            entry = SphU.entry("firstResource");
            // 被保护的业务逻辑
            return "Hello first sentinel demo!";
        } catch (BlockException e) {
            // 资源访问阻止，被限流或被降级
            e.printStackTrace();
            return "Block by sentinel!";
        } finally {
            if (entry != null) {
                entry.exit();
            }
        }
    }

    /**
     * if方式
     * @return
     */
    @GetMapping("/three")
    public String threeTest() {
        //定义资源
        if(SphO.entry("firstResource")) {
            // 被保护的业务逻辑
            try {
                return "Hello first sentinel demo!";
            } finally {
                SphO.exit();
            }
        } else {
            // 资源访问阻止，被限流或被降级
            return "Block by sentinel!";
        }
    }

    /**
     * 注解方式
     * @return
     */
    @GetMapping("/fourth")
    @SentinelResource(value = "firstResource", blockHandler = "fourthTestBlockHandle")
    public String fourthTest() {
       return "Hello first sentinel demo!";
    }

    /**
     * 降级方法
     * @return
     */
    public String fourthTestBlockHandle(BlockException e) {
        e.printStackTrace();
        return "Block by sentinel!";
    }

    @GetMapping("/fifth")
    public String fifthRest() {
        try {
            AsyncEntry asyncEntry = SphU.asyncEntry("firstResource");
            this.doAsync("sentinel", result -> {
                ContextUtil.runOnContext(asyncEntry.getAsyncContext(), () -> {
                    try {
                        // 此处嵌套正常的资源调用.
                        try(Entry entry = SphU.entry("anotherResource");) {
                            // Handle your result here.
                        } catch (BlockException ex) {
                            // Blocked for the result handler.
                        }
                    } finally {
                        asyncEntry.exit();
                    }
                });
                System.out.println(result);
            });
            return "Finish request" + System.currentTimeMillis();
        } catch (BlockException e) {
            e.printStackTrace();
            return "Block by sentinel!";
        }
    }

    private void doAsync(String userId, Consumer<String> handler) {
        CompletableFuture.runAsync(() -> {
            try {
                TimeUnit.SECONDS.sleep(3);
                String resp = "Hello" + userId + " " + System.currentTimeMillis();
                handler.accept(resp);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        });
    }

    //@PostConstruct
    private void initFlowRule() {
        List<FlowRule> rules = new ArrayList<>();
        FlowRule rule = new FlowRule();
        rule.setResource("firstResource");
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        rule.setCount(2);
        rules.add(rule);
        rule.setStrategy(RuleConstant.STRATEGY_CHAIN);
        FlowRuleManager.loadRules(rules);
    }

}
